package pl.diagnoser.server.persistance.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import pl.diagnoser.client.dto.SearchResultAttributesDTO;
import pl.diagnoser.client.dto.SearchResultDTO;
import pl.diagnoser.client.tools.SearchObjectAttribute;
import pl.diagnoser.server.persistance.map.SearchResult;
import pl.diagnoser.server.persistance.map.SearchResultAttributes;
import pl.diagnoser.server.persistance.tools.HibernateUtil;

public class SearchResultAttributesDao implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	public String saveSearchingAttributes(List<SearchObjectAttribute> objectAttributes, SearchResult searchResult) {
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		
		String info = "OK";
		for(SearchObjectAttribute objectAttribute : objectAttributes) {
			for(String attributeValue : objectAttribute.getAttributeValues(false)) {
				SearchResultAttributes searchResultAttributes = new SearchResultAttributes(searchResult, objectAttribute.getAttributeName(), attributeValue);
				Long generatedId = (Long) session.save(searchResultAttributes);
				if(generatedId == null) {
					info = "[SearchResultAttributes]: attributeName=" + objectAttribute.getAttributeName() + ", attributeValue=" + attributeValue;
					session.getTransaction().rollback();
					return info;
				}
			}
		}
		
		session.getTransaction().commit();
		session.close();
		return info;
	}
	
	public List<SearchResultAttributesDTO> getHistorySearchAttributes(long searchID) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		List<SearchResultAttributesDTO> searchHistoryAttributes = new ArrayList<SearchResultAttributesDTO>(0);
		SearchResult searchResult = (SearchResult) session.get(SearchResult.class, searchID);
		if(searchResult != null) {
			SearchResultDTO searchResultDTO = new SearchResultDao().createSearchResultDTO(searchResult, false);
			for(SearchResultAttributes searchResultHistoryAttribute : searchResult.getObjectAttributes()) {			
				searchHistoryAttributes.add(new SearchResultAttributesDTO(searchResultHistoryAttribute.getSearchResultAttributesId(),
																		  searchResultDTO,
																		  searchResultHistoryAttribute.getAttributeName(),
																		  searchResultHistoryAttribute.getAttributeValue()));
			}
		}
		
		session.getTransaction().commit();
		session.close();
		
		return searchHistoryAttributes;
	}
}
